package com.szm.userserver.mapperimpl;

import com.szm.userserver.entity.UserMongo;
import com.szm.userserver.mapper.UserMongoDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.awt.print.Pageable;
import java.util.List;

@Repository("UserMongoDao")
public class UserMongoDaoImpl implements UserMongoDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<UserMongo> findAll() {
        return mongoTemplate.findAll(UserMongo.class);
    }

    @Override
    public UserMongo getUserById(Integer id) {
        return mongoTemplate.findOne(new Query(Criteria.where("id").is(id)), UserMongo.class);
    }

    @Override
    public void insert(UserMongo userMongo) {
        mongoTemplate.insert(userMongo);
    }

    @Override
    public void update(UserMongo userMongo) {
        Criteria criteria = Criteria.where("id").is(userMongo.getId());
        Query query = new Query(criteria);
        Update update = Update.update("name", userMongo.getName()).set("age", userMongo.getAge());
        mongoTemplate.updateMulti(query, update, UserMongo.class);
    }

    @Override
    public void insertAll(List<UserMongo> userMongos) {
        mongoTemplate.insertAll(userMongos);
    }

    @Override
    public void remove(Integer id) {
        mongoTemplate.remove(new Query(Criteria.where("id").is(id)), UserMongo.class);
    }

    @Override
    public List<UserMongo> findByPage(UserMongo userMongo, Pageable pageable) {
        Query query = new Query();
        if (userMongo != null && userMongo.getName() != null) {
            Criteria criteria = Criteria.where("name").regex("^" + userMongo.getName());
            query=new Query(criteria);
        }

        return mongoTemplate.find(query,UserMongo.class);
    }

}
